package com.feishi.core.util.common;

import lombok.Data;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

@Data
public class GS1Util {
    static class Rule{
        String start;
        int min;
        int max;

        public Rule(String start, int min, int max) {
            this.start = start;
            this.min = min;
            this.max = max;
        }
    }
    public static List<Rule> rules=new ArrayList<>(){{
        add(new Rule("01",14,14));
        add(new Rule("11",6,6));
        add(new Rule("17",6,6));
        add(new Rule("10",1,24));
        add(new Rule("21",1,26));
    }};
    static class GS1AnalysisWrapper {
        Rule rule;
        String value;
        String left;
        int min;
        int max;
        List<GS1AnalysisWrapper> children=new ArrayList<>();

        public GS1AnalysisWrapper(Rule rule, String value, int min, int max) {
            this.rule = rule;
            this.value = value;
            this.min = min;
            this.max = max;
        }

        public GS1AnalysisWrapper(String value) {
            this.value = value;
        }

        public void next() {
            for (int i = min; i <=max ; i++) {
                String left=value.substring(i);
                for (Rule r : rules) {
                    GS1AnalysisWrapper result = check(left, r);
                    if(result!=null){
                        result.next();
                        children.add(result);
                    };
                }
            }
        }

        private GS1AnalysisWrapper check(String left, Rule r) {
            if(left.startsWith(r.start)&&left.length()>=r.start.length()+r.min){
                return new GS1AnalysisWrapper(r,left,r.min+r.start.length(),Math.min(r.max+r.start.length(),left.length()));
            }
            return null;
        }

        public List<List<String>> build() {
            String value=this.value;
            List<String> out=new ArrayList<>();
            List<List<String>> values=new ArrayList<>();
            for (GS1AnalysisWrapper child : children) {
                out.add(value.substring(0,value.length()-child.value.length()));
            }
            return values;
        }
    }

    public static GS1AnalysisWrapper analysis(String code){
        GS1AnalysisWrapper wrapper=new GS1AnalysisWrapper(null,code,0,0);
        wrapper.next();
        return wrapper;
    }

    public static void main(String[] args) {
        GS1AnalysisWrapper wrapper = new GS1AnalysisWrapper("01124565456545651112456310154221454");
        wrapper.next();
        List<List<String>> result=wrapper.build();
        System.out.println(result);
    }
}
